import Router from 'koa-router';
import parse from 'co-body';
import Kutils from '../../modules/Kutils';
import md5 from 'md5';


import { model as AppUpdList } from '../../models/appUpdList';
import { model as ClientMsg } from '../../models/clientMsg';
import { model as PrePrintOrder } from '../../models/prePrintOrder';


const prefix = '/';
const router = new Router();
const kutil = new Kutils();


const totalRex = new RegExp('总计:(\\S*)元');
const actualRex = new RegExp('应收:(\\S*)元');
const foodsRex = new RegExp('([\\u4e00-\\u9fa5]+)\\s+(\\d*)份');


router.get('mrc', 'mrc', function* dispatch() {
    const log = this.log.getLogger('REST:/mrc');

    const url = 'http://mrc.kuaihaowei.net/mrc/index.html?sys=KHL';

    log.info(`mrc url = ${url}`);
    this.redirect(url);
});


router.get('getKm', 'get_km', function* dispatch() {
    const log = this.log.getLogger('REST:get_km');

    const baseUrl = 'http://dist.kuaihaowei.net/km/setup/km-setup-{}.exe';
    const kmInfo = yield AppUpdList.findOne({ type: 'km', cat: 'xp_32' }).exec();

    if (!kmInfo) {
        this.throw('not found km config', 404);
    }

    const ver = kmInfo.url.match('km-setup-(\\S*).zip')[1];
    const url = kutil.formatStr(baseUrl, ver);

    log.info(`km url = ${url}`);
    this.redirect(url);
});

router.get('getDuba', 'get_duba', function* dispatch() {
    const log = this.log.getLogger('REST:get_duba');

    const url = 'http://cd002.www.duba.net/duba/install/2011/ever/duba161229_100_50.exe';

    log.info(`duba url = ${url}`);
    this.redirect(url);
});

router.post('getCmd', 'getCmd', function* dispatch() {
    const log = this.log.getLogger('REST:getCmd');

    const body = yield parse.json(this);
    const serialId = body.serialId;

    const cmds = yield ClientMsg.find({ serialId, isUsed: false }).exec();

    console.log(cmds);

    const result = [];
    for (const cmd of cmds) {
        result.push({
            param: cmd.param,
            data: cmd.data,
        });
    }
    log.info(`[client_test_getCmd] result: ${JSON.stringify(result)}`);

    yield ClientMsg.update(
        { serialId, isUsed: false }, { $set: { isUsed: true } }, { multi: true }).exec();

    this.body = result;
});

router.post('parse', 'parse', function* dispatch() {
    const log = this.log.getLogger('REST:parse');
    const body = yield parse.json(this);

    log.info(`[client_test_parse] result: ${JSON.stringify(body)}`);

    const param = body.param;
    const data = body.data;

    const lines = data.split('\n');

    const handleText = [];
    for (let line of lines) {
        line = line.replace('：', ':');
        line = line.replace('“', '"');
        line = line.replace('”', '"');
        line = line.replace('，', ',');
        line = line.replace('（', '(');
        line = line.replace('）', ')');
        handleText.push(line);
    }

    let total = 0;
    let actual = 0;
    const foods = [];

    for (const text of handleText) {
        if (total === 0) {
            const totalResult = totalRex.exec(text);
            if (totalResult) {
                total = Number(totalResult[1]);
                continue;
            }
        }
        if (actual === 0) {
            const actualResult = actualRex.exec(text);
            if (actualResult) {
                actual = Number(actualResult[1]);
                continue;
            }
        }

        const foodsResult = foodsRex.exec(text);
        if (foodsResult) {
            foods.push({
                name: foodsResult[1],
                num: Number(foodsResult[2]),
            });
        }
    }
    const tokenKey = 'dcHbTs';
    const order = yield new PrePrintOrder({
        sys: param.sys,
        wid: param.wid,
        tableId: param.tableId,
        tableNo: param.tableNo,
        opId: param.openId,
        total,
        actual,
        foods,
        tokenKey,
    }).save();

    const id = '_id';
    const msg = {
        sys: order.sys,
        openId: order.opId,
        tableId: order.tableId,
        objId: order[id],
        token: md5(order[id] + tokenKey).substring(8, 24),
        actualAmount: order.actual,
    };

    const headers = {};
    const typeId = '__TypeId__';
    headers[typeId] = 'com.kuaihaowei.models.warehouseTable.TicketReadyMsgReq';

    const ch = this.sendChannel;
    ch.publish(
        'wxtm-exchange',
        'wxtm',
        new Buffer(JSON.stringify(msg)),
        {
            contentEncoding: 'UTF-8',
            contentType: 'application/json',
            headers,
        });

    this.body = msg;
});

export {
    prefix,
    router,
};
